import Taro from '@tarojs/taro';
import { create } from 'zustand';
import { immer } from 'zustand/middleware/immer';
import { fetchDCityTreeList } from '@/business/services/common/common';
import { handleCityTree } from '@/utils/format';

/**
 * @description 地区选择树状列表(带发帖数)
 * @author Shawn
 */

type RequestFunction = () => Promise<void>;

type State = {
  // 地区选择树状列表
  dCityTreeList: any;
};

type Actions = {
  // 获取地区选择树状列表
  getdCityTreeList: RequestFunction;
};

const initialState: State = {
  dCityTreeList: [],
};

export const dCityTreeListStore = create<State & Actions>()(
  immer((set, get) => ({
    ...initialState,

    /**
     * 获取地区选择树状列表
     */
    getdCityTreeList: async () => {
      const cityTreeList = get().dCityTreeList;
      if (cityTreeList && cityTreeList.length > 0) return;
      try {
        Taro.showLoading({
          title: '加载中',
        });
        const res = await fetchDCityTreeList({});
        let rawCitys = res.data;
        handleCityTree(rawCitys);

        rawCitys = [
          {
            id: '00',
            name: '全国',
            demandCount: rawCitys.reduce((acc: number, p: any) => acc + (p.demandCount || 0), 0),
            children: [
              {
                name: '全部',
                id: '',
                children: [
                  {
                    name: '全部',
                    id: '',
                  },
                ],
              },
            ],
          },
          ...rawCitys,
        ];
        set((state) => {
          state.dCityTreeList = rawCitys;
        });
      } catch (error) {
        console.log('获取地区选择树状列表失败', error);
      } finally {
        Taro.hideLoading();
      }
    },
  })),
);
